package com.zhao.customer.controller;


import com.google.code.kaptcha.Constants;
import com.zhao.customer.dao.UserDao;
import com.zhao.customer.entity.User;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
@WebServlet("/login.do")
public class LoginController extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.sendRedirect("login.jsp");//重定向的目的:防止表单重复提交
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String name = req.getParameter("name");
        String password = req.getParameter("password");
        String code = req.getParameter("code");
        String scode = (String)req.getSession().getAttribute(Constants.KAPTCHA_SESSION_KEY);
        if (scode == null) {
            resp.sendRedirect("login.jsp");
        }else {
            if(!scode.equals(code)){
                resp.sendRedirect("login.jsp");
            }else {
                if ((!name.isEmpty() || !name.equals(" ")) && (!password.isEmpty() || !password.equals(" "))) {
                    User user = null;
                    try {
                        user = new UserDao().selectByName(name);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    if(name.equals(user.getName())&&password.equals(user.getPassword())){
                        System.out.println("可以了");
                    }
                } else {
                    resp.sendRedirect("login.jsp");
                }
            }
        }
    }
}
